import { filterObj } from '@/utils/util';
import {deleteAction, getAction, postdeleteAction} from '@/api/manage'
import qs from 'qs'
import Vue from 'vue'
import store from "@/store";
import { ACCESS_TOKEN } from "@/store/mutation-types"

export default {
  data () {
    /* eslint-disable */
    return {
      // 设置属性
      url: {
        list: '',              // 数据列表接口，API地址
        delete: '',            // 删除接口，API地址
        export: ''             // 导出接口，API地址
      },
      // 默认属性
      queryParam: {},             // 查询条件
      dataList: [],               // 数据列表
      /* 排序参数 */
      isorter: {
        column: 'create_date',
        order: 'desc',
      },
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      loading: false,     // 数据列表，loading状态
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      modelFormVisible: false   // 新增／更新，弹窗visible状态
    }
    /* eslint-enable */
  },
  // 此页面是否在创建时，调用查询数据列表接口？
  created () {
    if (this.disableMixinCreated) {
      console.log(' -- mixin created -- ')
      this.loadData()
    }
  },
  // 此页面是否在激活（进入）时，调用查询数据列表接口？
  activated () {
    if (this.disableMixinActivated) {
      this.loadData()
    }
  },
  computed: {
    //token header
    tokenHeader(){
      let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
      return head;
    }
  },
  methods: {
    // 获取数据列表
    loadData: function () {
      if (!this.url.list) {
        return this.$message.warning("请设置url.list属性!")
      }
      this.loading = true
      var params = this.getQueryParams();//查询条件
      getAction(this.url.list, params).then((res) => {
        this.loading = false
        if (res.success) {
          this.dataList = res.result.list || res.result
          if (res.result.total) {
            this.ipagination.total = Number(res.result.total);
          } else {
            this.ipagination.total = 0;
          }
        } else {
          this.$message.error(res.message)
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getQueryParams () {
      //获取查询条件
      var param = Object.assign({}, this.queryParam);
      param.order = this.isorter.order
      param.orderField = this.isorter.column
      param.page = this.ipagination.current;
      param.limit = this.ipagination.pageSize;
      return filterObj(param);
    },
    // 多选
    onSelectChange (selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectionRows = selectionRows;
    },
    onClearSelected () {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    tableChangeHandle (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" === sorter.order ? "asc" : "desc"
      }
      this.ipagination = pagination;
      this.loadData();
    },
    searchQuery () {
      this.ipagination.current = 1
      this.loadData()
      // 点击查询清空列表选中行
      this.onClearSelected()
    },
    searchReset() {
      this.queryParam = {}
      this.loadData();
    },
    // 删除
    deleteHandle: function (id) {
      if (!this.url.delete) {
        return this.$message.warning("请设置url.delete属性!")
      }
      var that = this;
      postdeleteAction(that.url.delete, [id]).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.error(res.message);
        }
      });
    },
    batchDeleteHandle: function () {
      if (!this.url.delete) {
        return this.$message.warning("请设置url.delete属性!")
      }
      if (this.selectedRowKeys.length <= 0) {
        return this.$message.warning('请选择一条记录！');
      }
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          that.loading = true;
          deleteAction(that.url.delete, that.selectedRowKeys).then((res) => {
            if (res.success) {
              //重新计算分页问题
              that.reCalculatePage(that.selectedRowKeys.length)
              that.$message.success(res.message);
              that.loadData();
              that.onClearSelected();
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.loading = false;
          });
        }
      });
    },
    reCalculatePage (count) {
      //总数量-count
      let total = this.ipagination.total - count;
      //获取删除后的分页数
      let currentIndex = Math.ceil(total / this.ipagination.pageSize);
      //删除后的分页数<所在当前页
      if (currentIndex < this.ipagination.current) {
        this.ipagination.current = currentIndex;
      }
      console.log('currentIndex', currentIndex)
    },
    // 新增 / 修改
    modelFormHandle (id) {
      this.modelFormVisible = true
      this.$nextTick(() => {
        this.$refs.modelForm.dataForm.id = id
        this.$refs.modelForm.init()
      })
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      this.loadData();
      //清空列表选中
      this.onClearSelected()
    },
    /* 导入 */
    handleImportExcel (info) {
      this.loading = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.loading = false
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName, details } } = info.file.response
            for (let i = 0; i < details.length; i++) {
              details[i] = <div>{ details[i] }</div>
            }
            this.$warning({
              title: message,
              content: (<div>
                  <span>{ msg }</span><br />
                  <div>{ details }</div>
                </div>
              )
            })
          } else {
            this.$message.success(info.file.response.message || `${ info.file.name } 文件上传成功`)
          }
          this.loadData()
        } else {
          this.$message.error(`${ info.file.name } ${ info.file.response.message }.`)
        }
      } else if (info.file.status === 'error') {
        this.loading = false
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${ info.file.msg } `)
        }
      }
    },
    // 导出
    exportHandle (fileName) {
      var params = qs.stringify({
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),
        fileName: fileName,
        ...this.queryParam
      })
      window.location.href = `${ window._CONFIG['domianURL'] }${ this.url.export }?${ params }`
    },
    // 下载文件
    downloadFile (data, fileName) {
      if (!data) {
        return this.$message.warning("文件下载失败")
      } else {
        this.$message.success({
          content: '下载成功',
          duration: 1,
          onClose: () => {
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), fileName + '.xlsx')
            } else {
              let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName + '.xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link); //下载完成移除元素
              window.URL.revokeObjectURL(url); //释放掉blob对象
            }
          }
        })
      }
    }
  }
}
